#include <QValidator>
#include <QLineEdit>
#include <QPainter>

#include "floatdelegate.h"
#include "defs.h"

FloatDelegate::FloatDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QString FloatDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
    if ( !value.toString().isEmpty() && value.isValid())
    {
        bool ok = false;
        double val = value.toDouble(&ok);
        if (ok && val>0.0f)
        {
            return doubleToQString(val);
        } else {
            return QStyledItemDelegate::displayText(NOT_CORRECT, locale);
        }
    } else
        return QStyledItemDelegate::displayText(QString("-"), locale);
}

QWidget* FloatDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const
{
    Q_UNUSED(index);
    QLineEdit *editor = new QLineEdit(parent);
    QDoubleValidator *doubleValidator = new QDoubleValidator(parent);
    editor->setValidator( doubleValidator );
    return editor;
}

void FloatDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QLineEdit *edt = qobject_cast<QLineEdit*>(editor);
    edt->setText( index.data().toString() );
}

void FloatDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QLineEdit *edt = qobject_cast<QLineEdit*>(editor);
    model->setData( index, edt->text() );
}
